package com.dlc.shop.platform.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dlc.shop.bean.bo.RefundInfoBo;
import com.dlc.shop.bean.dto.OrderRefundDto;
import com.dlc.shop.bean.enums.ReturnMoneyStsType;
import com.dlc.shop.bean.enums.SendType;
import com.dlc.shop.bean.model.*;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.enums.PayType;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.common.util.DateUtils;
import com.dlc.shop.common.util.ExceptionUtils;
import com.dlc.shop.common.util.IpHelper;
import com.dlc.shop.dao.PayInfoMapper;
import com.dlc.shop.huifu.DemoTestConstants;
import com.dlc.shop.manager.impl.PayManager;
import com.dlc.shop.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author yami
 */
@Slf4j
@Component
@AllArgsConstructor
public class OrderRefundTask {

    private final OrderRefundService orderRefundService;
    private final NotifyTemplateService notifyTemplateService;
    private final RefundInfoService refundInfoService;
    private final PayManager payManager;
    private final RedissonClient redissonClient;
    private final OrderService orderService;
    private final SkuService skuService;
    private final ShopDetailService shopDetailService;
    private final PayInfoMapper payInfoMapper;
    /**
     * 超时取消退款和发放退款互斥锁
     */
    private static final String LOCK_REFUND_HANDLE_PREFIX = "redisson_lock:refund_handle:";


    /**
     * 取消申请超时的订单，无论该超时订单处于任何状态
     */
    @XxlJob("cancelWhenTimeOut")
    public void cancelWhenTimeOut() {
        log.info("==============订单退款超时处理开始===================");
        // 设定时间值
        Date date = DateUtil.offsetDay(new Date(), -Constant.MAX_REFUND_APPLY_TIME);
        // 获取待处理的退款订单
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .in(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.closeStatus())
                .lt(OrderRefund::getApplyTime, date));
        if (CollectionUtils.isNotEmpty(orderRefundList)) {
            for (OrderRefund orderRefund : orderRefundList) {
                RLock lock = redissonClient.getLock(LOCK_REFUND_HANDLE_PREFIX + orderRefund.getRefundSn());
                try {
                    lock.lock();
                    OrderRefund dbOrderRefund = orderRefundService.getById(orderRefund.getRefundId());
                    if (Objects.equals(dbOrderRefund.getReturnMoneySts(), ReturnMoneyStsType.PROCESSING.value())) {
                        // 商家处理状态，查询退款是否成功
                        RefundInfo dbRefundInfo = refundInfoService.getByRefundId(orderRefund.getRefundSn());
                        if (Objects.nonNull(dbRefundInfo)) {
                            String reqDate = "";
                            if (dbRefundInfo.getReqDate() == null) {
                                reqDate = DateUtils.parseDateToStr("yyyyMMdd", dbRefundInfo.getCreateTime());
                            } else {
                                reqDate = dbRefundInfo.getReqDate();
                            }
                            Boolean isSettled = false;
                            List<OrderItem> orderItems = orderRefundService.getOrderRefundByRefundSn(orderRefund.getRefundSn()).getOrderItems();
                            List<String> refundOrderNumbers = orderItems.stream().map(OrderItem::getOrderNumber).collect(Collectors.toList());
                            List<Order> orderPayInfoByOrderNumber = orderService.getOrderPayInfoByOrderNumber(refundOrderNumbers);
                            if (orderPayInfoByOrderNumber.size() >= 1) {
                                Order order = orderPayInfoByOrderNumber.get(0);
                                if (order.getIsSettled() == 1) {
                                    //多个订单如果一个结算了就都结算了
                                    isSettled = true;
                                    log.info(order.getOrderNumber() + "------->  此订单已经结算，所以走订单结算后退款");
                                }
                            }
                            Map<String, Object> extendInfoMap = new HashMap<>();
                            if (isSettled) {
                                extendInfoMap = getRefundExtendIsSettledInfos(dbOrderRefund.getRefundSn());
                            } else {
                                extendInfoMap = getRefundExtendInfos(dbRefundInfo.getPayNo(),
                                        "https://dlchm.cn/shop/apis/order/refund/result/huifu", dbOrderRefund.getRefundSn());
                            }
                            RefundInfoBo refundInfoBo = payManager.getRefundHuiFuInfo(
                                    PayType.instance(dbRefundInfo.getPayType()), dbRefundInfo.getPayNo(),
                                    dbRefundInfo.getPaySysType(), dbRefundInfo.getRefundId(), reqDate, isSettled, extendInfoMap);
                            if (refundInfoBo.getIsRefundSuccess()) {
                                // 退款回调
                                refundSuccess(dbRefundInfo, refundInfoBo);
                                continue;
                            }
                        }
                    }
                    if (ReturnMoneyStsType.shouldClous(dbOrderRefund.getReturnMoneySts())) {
                        log.info("退款订单超时关闭" + dbOrderRefund.getRefundSn());
                        orderRefundService.cancelWhenTimeOut(orderRefund);
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
        log.info("==============订单退款超时处理结束===================");
    }

    /**
     * 非必填字段 汇付15天以内的退款
     *
     * @return
     */
    private Map<String, Object> getRefundExtendInfos(String payno, String url, String refundSn) {
        PayInfo payInfo = payInfoMapper.selectOne(new LambdaQueryWrapper<PayInfo>()
                .eq(PayInfo::getPayNo, payno));
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();
        // 原交易流水号
        extendInfoMap.put("org_req_seq_id", payInfo.getBizPayNo());
        //汇付 退款需要回调地址
        extendInfoMap.put("notify_url", url);
        // 设备信息
        Map<String, String> deviceInfo = new HashMap<>();
        if (IpHelper.getIpAddr() == null) {
            deviceInfo.put("ip_addr", "127.0.0.1");
        } else {
            deviceInfo.put("ip_addr", IpHelper.getIpAddr());
        }

        extendInfoMap.put("risk_check_data", JSON.toJSONString(deviceInfo));
        //List<Map<String, String>> acct_infos = new ArrayList<>();

        //根据 退款编号查询退了多少钱，并且退款是多少钱
        OrderRefundDto orderRefund = orderRefundService.getOrderRefundByRefundSn(refundSn);
        List<OrderItem> orderItems = orderRefund.getOrderItems();

        //查询供应商 汇付id
        JSONArray acct_infos = new JSONArray();
        String huifuId = shopDetailService.getShopDetailByShopId(orderRefund.getShopId()).getHuifuId();

        if (huifuId != null && !"".equals(huifuId)) {

            if (huifuId.equals(DemoTestConstants.DEMO_SYS_ID)) {
                Double orderAmount = orderRefund.getOrderAmount();
                log.info("蒂爱喜全额退款 ", orderAmount);
                JSONObject acct_info = new JSONObject();
                acct_info.put("div_amt", BigDecimal.valueOf(orderAmount).setScale(2, RoundingMode.HALF_UP));
                acct_info.put("huifu_id", DemoTestConstants.DEMO_SYS_ID);
                acct_info.put("part_loan_amt", BigDecimal.valueOf(orderAmount).setScale(2, RoundingMode.HALF_UP));
                acct_infos.add(acct_info);
                extendInfoMap.put("acct_split_bunch", acct_infos);
            } else {
                //多商品退款
                Double supplierPrice = 0.00;
                for (OrderItem orderItem : orderItems) {
                    if (orderItem.getRefundId() != null) {
                        continue;
                    }
                    Sku sku = skuService.getSkuBySkuId(orderItem.getSkuId());
                    log.info("sku的值是什么{}", sku.toString());
                    //一件商品可以有多个数量
                    supplierPrice += (sku.getSupplierPrice() * orderItem.getProdCount());
                }
                JSONObject acct_info_shop = new JSONObject();

                acct_info_shop.put("div_amt", BigDecimal.valueOf(supplierPrice).setScale(2, RoundingMode.HALF_UP));
                acct_info_shop.put("huifu_id", huifuId);
                acct_info_shop.put("part_loan_amt", BigDecimal.valueOf(supplierPrice).setScale(2, RoundingMode.HALF_UP));
                acct_infos.add(acct_info_shop);
                //剩下的由蒂爱喜承担
                Double orderAmount = orderRefund.getOrderAmount();
                BigDecimal orderAmountbig = new BigDecimal(orderAmount);
                BigDecimal supplierPricebig = new BigDecimal(supplierPrice);

                //BigDecimal求差
                BigDecimal dlcAmount = orderAmountbig.subtract(supplierPricebig).setScale(2, RoundingMode.HALF_UP);

                JSONObject acct_info = new JSONObject();
                acct_info.put("div_amt", dlcAmount);
                acct_info.put("huifu_id", DemoTestConstants.DEMO_SYS_ID);
                acct_info.put("part_loan_amt", dlcAmount);
                acct_infos.add(acct_info);
                extendInfoMap.put("acct_split_bunch", acct_infos);
            }
        }


        // 原交易微信支付宝的商户单号
        // extendInfoMap.put("org_party_order_id", "");
        // 原交易请求流水号
        // extendInfoMap.put("org_req_seq_id", "");
        // 分账对象
        // extendInfoMap.put("acct_split_bunch", getAcctSplitBunchRucan());
        // 聚合正扫微信拓展参数集合
        // extendInfoMap.put("wx_data", getWxData());
        // 数字货币扩展参数集合
        // extendInfoMap.put("digital_currency_data", getDigitalCurrencyData());
        // 补贴支付信息
        // extendInfoMap.put("combinedpay_data", getCombinedpayData());
        // 备注
        // extendInfoMap.put("remark", "");
        // 是否垫资退款
        // extendInfoMap.put("loan_flag", "");
        // 垫资承担者
        // extendInfoMap.put("loan_undertaker", "");
        // 垫资账户类型
        // extendInfoMap.put("loan_acct_type", "");
        // 安全信息
        // extendInfoMap.put("risk_check_data", getRiskCheckData());
        // 设备信息
        // extendInfoMap.put("terminal_device_data", getTerminalDeviceData());
        // 异步通知地址
        // extendInfoMap.put("notify_url", "");
        // 银联参数集合
        // extendInfoMap.put("unionpay_data", getUnionpayData());
        return extendInfoMap;
    }

    /**
     * 汇付 15天以后的退款 直接退款没有回调
     *
     * @param refundSn
     * @return
     */
    private Map<String, Object> getRefundExtendIsSettledInfos(String refundSn) {
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();

        //根据 退款编号查询退了多少钱，并且退款是多少钱
        OrderRefundDto orderRefund = orderRefundService.getOrderRefundByRefundSn(refundSn);
        List<OrderItem> orderItems = orderRefund.getOrderItems();
        //查询供应商 汇付id
        JSONArray acct_infos = new JSONArray();
        String huifuId = shopDetailService.getShopDetailByShopId(orderRefund.getShopId()).getHuifuId();

        if (huifuId != null && !"".equals(huifuId)) {

            if (huifuId.equals(DemoTestConstants.DEMO_SYS_ID)) {
                Double orderAmount = orderRefund.getOrderAmount();
                log.info("蒂爱喜全额退款 {}", orderAmount);
                JSONObject acct_info = new JSONObject();
                acct_info.put("div_amt", BigDecimal.valueOf(orderAmount).setScale(2, RoundingMode.HALF_UP));
                acct_info.put("huifu_id", DemoTestConstants.DEMO_SYS_ID);
                acct_info.put("part_loan_amt", BigDecimal.valueOf(orderAmount).setScale(2, RoundingMode.HALF_UP));
                acct_infos.add(acct_info);
                extendInfoMap.put("acct_split_bunch", acct_infos);
            } else {
                //多商品退款
                Double supplierPrice = 0.00;
                for (OrderItem orderItem : orderItems) {
                    if (orderItem.getRefundId() != null) {
                        continue;
                    }
                    Sku sku = skuService.getSkuBySkuId(orderItem.getSkuId());
                    log.info("sku的值是什么{}", sku.toString());
                    //一件商品可以有多个数量
                    supplierPrice += (sku.getSupplierPrice() * orderItem.getProdCount());
                }
                JSONObject acct_info_shop = new JSONObject();

                acct_info_shop.put("div_amt", BigDecimal.valueOf(supplierPrice).setScale(2, RoundingMode.HALF_UP));
                acct_info_shop.put("huifu_id", huifuId);
                acct_info_shop.put("part_loan_amt", BigDecimal.valueOf(supplierPrice).setScale(2, RoundingMode.HALF_UP));
                acct_infos.add(acct_info_shop);
                //剩下的由蒂爱喜承担
                Double orderAmount = orderRefund.getOrderAmount();
                BigDecimal orderAmountbig = new BigDecimal(orderAmount);
                BigDecimal supplierPricebig = new BigDecimal(supplierPrice);

                //BigDecimal求差
                BigDecimal dlcAmount = orderAmountbig.subtract(supplierPricebig).setScale(2, RoundingMode.HALF_UP);

                JSONObject acct_info = new JSONObject();
                acct_info.put("div_amt", dlcAmount);
                acct_info.put("huifu_id", DemoTestConstants.DEMO_SYS_ID);
                acct_info.put("part_loan_amt", dlcAmount);
                acct_infos.add(acct_info);
                extendInfoMap.put("acct_split_bunch", acct_infos);
            }
        }


        // 原交易微信支付宝的商户单号
        // extendInfoMap.put("org_party_order_id", "");
        // 原交易请求流水号
        // extendInfoMap.put("org_req_seq_id", "");
        // 分账对象
        // extendInfoMap.put("acct_split_bunch", getAcctSplitBunchRucan());
        // 聚合正扫微信拓展参数集合
        // extendInfoMap.put("wx_data", getWxData());
        // 数字货币扩展参数集合
        // extendInfoMap.put("digital_currency_data", getDigitalCurrencyData());
        // 补贴支付信息
        // extendInfoMap.put("combinedpay_data", getCombinedpayData());
        // 备注
        // extendInfoMap.put("remark", "");
        // 是否垫资退款
        // extendInfoMap.put("loan_flag", "");
        // 垫资承担者
        // extendInfoMap.put("loan_undertaker", "");
        // 垫资账户类型
        // extendInfoMap.put("loan_acct_type", "");
        // 安全信息
        // extendInfoMap.put("risk_check_data", getRiskCheckData());
        // 设备信息
        // extendInfoMap.put("terminal_device_data", getTerminalDeviceData());
        // 异步通知地址
        // extendInfoMap.put("notify_url", "");
        // 银联参数集合
        // extendInfoMap.put("unionpay_data", getUnionpayData());
        return extendInfoMap;
    }

    private void refundSuccess(RefundInfo dbRefundInfo, RefundInfoBo refundInfoBo) {
        log.info("退款单号{}退款成功，回调开始....", dbRefundInfo.getRefundId());
        RefundInfo refundInfo = refundInfoService.getOne(new LambdaQueryWrapper<RefundInfo>().eq(RefundInfo::getRefundId, dbRefundInfo.getRefundId()));
        refundInfo.setPayRefundId(refundInfoBo.getBizRefundNo());
        // 主动查单，退款成功的给与回调
        refundInfoService.refundSuccess(refundInfo);
    }

    /**
     * 退款临近超时提醒,每12小时执行发送一次的提醒
     */
    @XxlJob("pressRefundOrder")
    public void pressRefundOrder() {
        log.info("==============订单退款超时提醒开始===================");
        // 临时超时时间为 最大申请时间 - 12小时
        Integer overTime = Constant.MAX_REFUND_APPLY_TIME * 24;
        Date date = DateUtil.offsetHour(new Date(), Constant.MAX_REFUND_HOUR - overTime);
        Date overDate = DateUtil.offsetDay(new Date(), -Constant.MAX_REFUND_APPLY_TIME);
        // 获取临近超时的退款订单,大于超时时间，小于临时时间
        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .in(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.closeStatus())
                .gt(OrderRefund::getApplyTime, overDate)
                .lt(OrderRefund::getApplyTime, date));
        if (CollectionUtils.isNotEmpty(orderRefundList)) {
            List<OrderRefundDto> orderRefundDtos = BeanUtil.mapAsList(orderRefundList, OrderRefundDto.class);
            orderRefundDtos = orderRefundDtos.stream().filter(distinctByKey(OrderRefundDto::getUserId)).collect(Collectors.toList());
            for (OrderRefundDto orderRefundDto : orderRefundDtos) {
                notifyTemplateService.sendNotifyByRefund(orderRefundDto, SendType.REFUND_OUT_TIME);
            }
        }
        log.info("==============退款临近超时提醒结束===================");
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 发放退款定时任务，给十分钟之前还没有收到退款回调的订单重新发放退款
     * 一分钟执行一次
     */
    @XxlJob("refundRequest")
    public void refundRequest() {
        log.info("==============发放退款定时任务开始===================");
        // 找到十分钟之前已经处理退款但是发放退款失败的退款订单
        List<OrderRefundDto> shouldRefundRequestList = orderRefundService.listShouldRefundRequest();
        if (CollUtil.isEmpty(shouldRefundRequestList)) {
            return;
        }
        // 给发放退款失败的订单重新发放一次
        for (OrderRefundDto orderRefundDto : shouldRefundRequestList) {
            RLock lock = redissonClient.getLock(LOCK_REFUND_HANDLE_PREFIX + orderRefundDto.getRefundSn());
            try {
                lock.lock();
                OrderRefund dbOrderRefund = orderRefundService.getById(orderRefundDto.getRefundId());
                if (Objects.equals(dbOrderRefund.getReturnMoneySts(), ReturnMoneyStsType.PROCESSING.value())) {
                    // 商家处理状态，查询退款是否成功
                    RefundInfo dbRefundInfo = refundInfoService.getByRefundId(dbOrderRefund.getRefundSn());
                    if (Objects.nonNull(dbRefundInfo)) {
                        // 申请退款成功，没有回调
                        log.info("退款单号为{}的订单开始进行退款查单", orderRefundDto.getRefundSn());
                        String reqDate = "";
                        if (dbRefundInfo.getReqDate() == null) {
                            log.info("如果 汇付退款reqDate 为null或者为空，这是历史遗留订单");
                            // RefundInfoBo refundInfoBo = payManager.getRefundInfo(PayType.instance(dbRefundInfo.getPayType()),
                            //         dbRefundInfo.getPayNo(), dbRefundInfo.getPaySysType(), dbRefundInfo.getRefundId());
                            // if (refundInfoBo.getIsRefundSuccess()) {
                            //     // 退款回调
                            //     refundSuccess(dbRefundInfo, refundInfoBo);
                            // }
                            continue;
                            //reqDate = DateUtils.dateTime( dbRefundInfo.getCreateTime());
                        } else {
                            reqDate = dbRefundInfo.getReqDate();
                        }
                        Boolean isSettled = false;
                        List<OrderItem> orderItems = orderRefundService.getOrderRefundByRefundSn(dbOrderRefund.getRefundSn()).getOrderItems();
                        List<String> refundOrderNumbers = orderItems.stream().map(OrderItem::getOrderNumber).collect(Collectors.toList());
                        List<Order> orderPayInfoByOrderNumber = orderService.getOrderPayInfoByOrderNumber(refundOrderNumbers);
                        if (orderPayInfoByOrderNumber.size() >= 1) {
                            Order order = orderPayInfoByOrderNumber.get(0);
                            if (order.getIsSettled() == 1) {
                                //多个订单如果一个结算了就都结算了
                                isSettled = true;
                                log.info(order.getOrderNumber() + "------->  此订单已经结算，所以走订单结算后退款");
                            }
                        }
                        Map<String, Object> extendInfoMap = getRefundExtendIsSettledInfos(dbOrderRefund.getRefundSn());
                        RefundInfoBo refundInfoBo = payManager.getRefundHuiFuInfo(PayType.instance(dbRefundInfo.getPayType()),
                                dbRefundInfo.getPayNo(), dbRefundInfo.getPaySysType(), dbRefundInfo.getRefundId(), reqDate, isSettled, extendInfoMap);
                        if (refundInfoBo.getIsRefundSuccess()) {
                            // 退款回调
                            refundSuccess(dbRefundInfo, refundInfoBo);
                        }
                    } else {
                        // 申请退款失败，重新申请
                        log.info("退款单号为{}的订单开始进行发放退款", orderRefundDto.getRefundSn());
                        // 提交退款请求
                        orderRefundService.submitWxRefund(orderRefundDto);
                    }
                }
            } catch (Exception e) {
                log.info("退款单号:{}订单发放退款失败，原因为:{}", orderRefundDto.getRefundSn(), ExceptionUtils.getRunException(e));
            } finally {
                lock.unlock();
            }
        }
        this.refundOrderStock();
        log.info("==============发放退款定时任务结束===================");
    }

    /**
     * 因为支付宝电脑支付订单全额退款成功是没有退款回调的，所以需要该定时任务定时执行
     * 调用主动查单 查十秒钟前,两小时内还没回调的支付宝电脑支付订单退款的状态
     * 一分钟执行一次
     */
    // @XxlJob("updateAliPayRefundStatus")
//    public void updateAliPayRefundStatus() {
//        log.info("==============支付宝退款订单查单开始===================");
//        List<RefundInfo> refundInfoList = refundInfoService.listAliPayRefund();
//        if (CollUtil.isEmpty(refundInfoList)) {
//            return;
//        }
//        for (RefundInfo dbRefundInfo : refundInfoList) {
//            RLock lock = redissonClient.getLock(LOCK_REFUND_HANDLE_PREFIX + dbRefundInfo.getRefundId());
//            try {
//                lock.lock();
//                String reqDate = "";
//                if (dbRefundInfo.getReqDate() == null) {
//                    reqDate = DateUtils.parseDateToStr("yyyyMMdd", dbRefundInfo.getCreateTime());
//                } else {
//                    reqDate = dbRefundInfo.getReqDate();
//                }
//                Boolean isSettled = false;
//                List<OrderItem> orderItems = orderRefundService.getOrderRefundByRefundSn(dbRefundInfo.getPayRefundId()).getOrderItems();
//                List<String> refundOrderNumbers = orderItems.stream().map(OrderItem::getOrderNumber).collect(Collectors.toList());
//                List<Order> orderPayInfoByOrderNumber = orderService.getOrderPayInfoByOrderNumber(refundOrderNumbers);
//                if (orderPayInfoByOrderNumber.size() >= 1) {
//                    Order order = orderPayInfoByOrderNumber.get(0);
//                    if (order.getIsSettled() == 1) {
//                        //多个订单如果一个结算了就都结算了
//                        isSettled = true;
//                        log.info(order.getOrderNumber() + "------->  此订单已经结算，所以走订单结算后退款");
//                    }
//                }
//                Map<String, Object> extendInfoMap = getRefundExtendIsSettledInfos(dbOrderRefund.getRefundSn());
//                RefundInfoBo refundInfoBo = payManager.getRefundHuiFuInfo(PayType.instance(dbRefundInfo.getPayType()),
//                        dbRefundInfo.getPayNo(), dbRefundInfo.getPaySysType(), dbRefundInfo.getRefundId(), reqDate,isSettled,extendInfoMap);
//                if (!refundInfoBo.getIsRefundSuccess()) {
//                    continue;
//                }
//                // 退款回调
//                refundSuccess(dbRefundInfo, refundInfoBo);
//            } finally {
//                lock.unlock();
//            }
//        }
//        log.info("==============支付宝退款订单查单结束===================");
//    }

    /**
     * 执行平台介入超时处理，超时则默认平台不同意退款
     */
    @XxlJob("refundInterventionTimeOut")
    public void cancelRefundInterventionTimeOut() {
        XxlJobHelper.log("执行平台介入超时处理，超时默认平台不同意退款");
        orderRefundService.cancelRefundInterventionTimeOut();
    }

    /**
     * 执行订单退款库存处理，根据退款订单的状态，决定回退退款还原的库存或者确认库存还原
     */
    @XxlJob("refundOrderStock")
    public void refundOrderStock() {
        XxlJobHelper.log("执行订单退款库存处理，根据退款订单的状态，决定回退退款还原的库存或者确认库存还原");
        try {
            orderRefundService.refundOrderStock();
        } catch (Exception e) {
            log.error("退款库存：",ExceptionUtils.getRunException(e));
        }
    }
}
